<?php

namespace app\http\middleware;

use think\Controller;
use app\model\Admin;
use app\model\Role;
use think\Db;

/**
 * 后台中间件Manage
 */
class Manage extends Controller
{
    public function handle($request, \Closure $next)
    {
        
        if(get_is_ip() === false){
            Session("auth_admin",null);
            return $this->error('该IP已列入黑名单','/manage/login');
        }
        $admin_auth = Session("auth_admin");
        if(!$admin_auth){
            return $this->error('登录超时','/manage/login');
        }
        $_auth_admin = Admin::get_auth($admin_auth['auth_admin_id']);
        if($_auth_admin['type'] == 2){
            Session("auth_admin",null);
            return $this->error('账号已禁用，请联系管理员解禁','/manage/login');
        }
        //单点登录
        if($admin_auth['key'] != $_auth_admin['key']){
            Session("auth_admin",null);
            return $this->error('账号在其他地方登陆','/manage/login');
        }
        //获取当前操作路由
        $url = rtrim(str_replace('//','',strip_tags($request->routeInfo()['rule'])),'/');
        
        if($url != 'manage' && $url !="manage/welcome" && $url !="manage/home"){
            //超级管理员开放所有权限
            if($admin_auth['role_id'] !== 1){
                //当前菜单id是否在当前角色里面
                if(!in_array(__menu([$url]),explode(",",$this->get_role($admin_auth['role_id'])))){
                    return $this->error("权限不够");
                }
            }
        }
        //绑定谷歌
        if(empty($_auth_admin['googl_secret'])){
            get_google('/manage/google',$admin_auth['user_name']);
        }
        //获取菜单
        if($admin_auth['role_id'] == 1){//超级管理员
            $menu = __menu();
        }else{
            $action = $this->get_role($admin_auth['role_id']);
            if(empty($action)){
                $menu = array();
            }else{
                $menu = __menu($action,1,2);//根据权限获取对应的菜单
            }
        } 
        $redis = new \Predis\Client();
        $admin_auth['web'] = $redis->get('web');
        $this->assign("menu",getTree($menu));//菜单
        $this->assign("admin_auth",$admin_auth);//登录信息
        $request->admin_auth = $admin_auth;//像控制器传递参数
            
        return $next($request);
    }
    /**
     * Undocumented 获取当前账号角色权限id
     *
     * @param [type] $id
     * @return void
     */
    public function get_role($id){
       
        $info = get_one('role',$id);
       
        if(!empty($info)){
            return $info['action'];
        }
        return Role::where("id",$id)->value("action");
    }
   
}
